package com.ruoyi.collect.hydrology.service;


import com.ruoyi.collect.hydrology.manager.SwjcParser;
import com.ruoyi.collect.hydrology.model.CollectorMapperDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.Charsets;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class CollectorManager {

    @Resource
    private CollectorMapperDto mapper;

    private List<Thread> thread = new ArrayList<>();

    @PostConstruct
    public void postConstruct() {
        log.info("collector: [{}]", mapper.isEnable());
        if (!mapper.isEnable()) {
            return;
        }
        startCollect();
    }
    public void startCollect() {
        String data = mapper.getData();
        if (StringUtils.hasText(data)) {
            thread.add(new CollectTemplate(
                    new CollectFileReader(data),
                    new CollectFileFilter(),
                    new SwjcParser(mapper, Charsets.UTF_8),
                    mapper,
                    "SWJC"));
        }

        thread.forEach(Thread::start);
        log.info("collector_start");
    }
    @PreDestroy
    public void preDestroy() {
        thread.forEach(Thread::interrupt);
        log.info("predestroy");
    }
}
